#!/usr/bin/perl
use strict;
use warnings;
use CGI ();

#use CGI::Carp qw(fatalsToBrowser);
use MIME::Lite ();
use OCF::Centre;
use Storable qw(lock_store);

my @centres;

while ( my $line = <> ) {
    chomp $line;
    if ( $line =~ /^(.+?)\s*\t+(.+?)\s*\t+(.+?)\s+(\d{4})/ ) {
        my $centre_details = {};
        $centre_details->{state}      = $1;
        $centre_details->{centre}     = $2;
        $centre_details->{university} = $3;
        $centre_details->{year}       = $4;

        if ( $centre_details->{centre} =~ /\(formerly\s+(.+?)\)/i ) {
            my $old_name = $1;
            my $new_name = $centre_details->{centre};
            $new_name =~ s/\(formerly\s+(.+?)\)//g;

            # olde name
            $centre_details->{centre} = $old_name;
            add_or_update_centre($centre_details);

            # new name
            $centre_details->{centre} = $new_name;
            add_or_update_centre($centre_details);
        } ## end if ( $centre_details->{centre} =~ /\(formerly OCF(.+?)\)/)
        else {
            add_or_update_centre($centre_details);
        }

    } ## end if ( $line =~ /^(.+?)\s*\t+(.+?)\s*\t+(.+?)\s+(\d{4})/)
    else {
        warn $line;
    }
} ## end while ( my $line = <> )

sub add_or_update_centre {
    my $centre_details = shift || {};
    $centre_details->{centre} =~ s/^OCF\s+//g;
    my $c = OCF::Centre->new( 'name' => $centre_details->{centre} );
    my $rv = $c->load( 'speculative' => 1 );
    if ( !$rv ) {
        $c->state( $centre_details->{state} );
        $c->university( $centre_details->{university} );
        $c->year_affiliated( $centre_details->{year} );
        $c->save();
    } ## end if ( !$rv )

} ## end sub add_or_update_centre
